package com.core.common.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.core.sys.service.IUserService;
import com.core.sys.vo.ActiveUserVo;
import com.utils.DigestUtil;


@Controller
public class LoginController {

	@Resource
	private IUserService userService;

	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login(HttpServletResponse response, HttpServletRequest request) throws IOException {
		HttpSession session = request.getSession();
		ActiveUserVo acticeUser = (ActiveUserVo) session.getAttribute("activeUser");
		if (acticeUser != null) {
			return "redirect:/admin/index";
		}
		return "/admin/account/login";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String loginPost(@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		ActiveUserVo acticeUser = userService.getActiveUserByName(username);
		if (acticeUser != null) {
			if(username.equals(acticeUser.getUserName())){
				password = DigestUtil.getMD5(password);
				if (password.equals(acticeUser.getPassWord())) {
					acticeUser.setPassWord("");
					HttpSession session = request.getSession();
					session.setAttribute("activeUser", acticeUser);
					return "redirect:/admin/index";
				} else {
					request.setAttribute("loginFlag", 1);
					return "/admin/account/login";
				}
			} else {
				request.setAttribute("loginFlag", -1);
				return "/admin/account/login";
			}
		} else {
			request.setAttribute("loginFlag", -1);
			return "/admin/account/login";
		}
	}

	@RequestMapping(value = "/loginOut", method = { RequestMethod.GET })
	public String loginOut(HttpServletResponse response, HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/login";
	}

	@RequestMapping(value = "/refuse", method = { RequestMethod.GET })
	public String refuse(HttpServletResponse response, HttpServletRequest request) {

		return "/admin/account/refuse";
	}

}
